#include <my_head.h>
#include "SocketIO.h"
#include <cerrno>
SocketIO::SocketIO(int fd)
:_fd(fd)
{}
int SocketIO::readn(char *buf,int len){
    int left = len;
    char *pbuf = buf;
    while(left > 0){
        int ret = recv(_fd,pbuf,len,0);
        if(ret == -1 && errno == EINTR){
            continue;
        }else if(ret == -1){
            perror("recv");
            return ret;
        }else if(ret == 0){
            return len - left;
        }else{
            left -= ret;
            pbuf +=ret;
        }
    }
    return len;
}
int SocketIO::sendn(const char *buf,int len){
    int left = len;
    const char *pbuf = buf;
    while(left > 0){
        int ret = send(_fd,pbuf,len,0);
        if(ret < 0){
            perror("send");
            return ret;
        }else{
            left -=ret;
            pbuf +=ret;
        }
    }
    return len;
}
int SocketIO::recvPeek(char *buf,int max){
    int ret = 0;
    do{
        ret = recv(_fd,buf,max,MSG_PEEK);
    }while(ret < 0 && errno == EINTR);
    if(ret < 0){
        perror("recv");
    }
    return ret;
}
int SocketIO::readline(char *buf,int max){
    int left = max - 1;
    char *pbuf = buf;
    int total = 0;
    while(left > 0){
        int ret = recvPeek(pbuf,left);

        //找'\n'
        for(int i =0;i<ret;++i){
            if(pbuf[i] == '\n'){
                int size = i + 1;
                ret = readn(pbuf,size);
                total += size;
                pbuf[i] = '\0';
                return total;
            }
        }
        //没找到'\n'
        ret = readn(pbuf,ret);
        left -= ret;
        pbuf += ret;
        total +=ret;
    }
    buf[max-1] = '\0';
    return max - 1;
}
int SocketIO::readPacket(Packet & packet){
    //Type(1字节) length(1字节) value(若干字节)
    int type,length;
    readn((char *)& type,sizeof(type));
    readn((char *)& length,sizeof(length));

    if(length > 0){
        char *pbuf = new char[length + 1]();
        int ret = readn(pbuf,length);//读取的字节数
        packet._type = type;
        packet._length = length;
        packet._msg.assign(pbuf,length);
        delete [] pbuf;
        return ret + 8;//读取的字节数加上Type和length各四个字节
    }
    return 8;//如果length为0的话说明没有信息
}